package com.yunda.nebula.gateway.beandefine;

import com.yunda.nebula.gateway.core.DataChangedListener;
import com.yunda.nebula.gateway.core.entity.ConfigData;
import com.yunda.nebula.gateway.core.enums.DataEventTypeEnum;
import com.yunda.nebula.gateway.service.RouteDefinitionPraseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * \* User: wei.zhang
 * \* Date: 2020/9/17 14:14
 * \* Description:
 *
 * @author wei.zhang
 * \
 */
@Service
@Slf4j
public class AppDataChangedListener implements DataChangedListener {

    @Autowired
    private RouteDefinitionRepository routeDefinitionRepository;

    @Autowired
    private RouteDefinitionPraseService routeDefinitionPraseService;

    @Override
    public void onAppChanged(ConfigData configData, DataEventTypeEnum dataEvent) {
        if (dataEvent.equals(DataEventTypeEnum.CREATE)){
            Mono<RouteDefinition> mono = Mono.just(routeDefinitionPraseService.parse(configData));
            routeDefinitionRepository.save(mono).subscribe();

        }else if (dataEvent.equals(DataEventTypeEnum.UPDATE)){
            Mono<String> mono = Mono.just(configData.getAppId());
            routeDefinitionRepository.delete(mono).subscribe();
            Mono<RouteDefinition> definitionMono = Mono.just(routeDefinitionPraseService.parse(configData));
            routeDefinitionRepository.save(definitionMono).subscribe();
        }else if (dataEvent.equals(DataEventTypeEnum.DELETE)){
            Mono<String> mono = Mono.just(configData.getAppId());
            routeDefinitionRepository.delete(mono).subscribe();
        }else {
            log.error("该事件没有监听 无法处理!!! 信息为 {},事件为 {}",configData,dataEvent);
        }
        return;
    }
}
